<?php
/**
 * 工具类文件，在这里写一些公用的函数
 * @package util
 */


 class Util {
 
 /**
  * 分页函数,风格为首页，上一页，下一页，最后一页
  *
  * @param Int totalNum 总的记录数
  * @param Int per_page 每页显示的数量
  * @param Int nowPage 当前页
  * @return  Array 关联数组
   array(
         'page'     => Array(
                             'totalnum'  => $totalNum,//总的数量
                             'totalpage' => $PageNum,//总的页数
                             'perpage'   => $PerPage,//每页显示多少数据
                             'first'     => $FirstNum,//第一页
                             'end'       => $EndNum,//最后一页
                             'previous'  => $previousNum,//前一页
                             'nowp'      => $nowPage,//当前页
                             'next'      => $nextNum//下一页
                             ),
         'start'    => $limitStart
                  );
  * @author RD
  */
public static function page ($totalNum = 0, $per_page = 10, $nowPage = 1)
 {
     /**总的页数**/
     $PageNum = ceil ($totalNum / $per_page);
     
     $nowPage = $nowPage > $PageNum ? $PageNum : $nowPage;
     $nowPage = $nowPage < 1 ? 1 : $nowPage;
     
     /**开始结束页数**/
     $FirstNum      = 1;
     $EndNum        = $PageNum;
     
     /**前一页，下一页**/
     $previousNum   = $nowPage - 1;
     $nextNum       = $nowPage + 1;
     
     $previousNum   = $previousNum < 1 ? 1 : $previousNum;
     $nextNum       = $nextNum > $PageNum ? $PageNum : $nextNum;
     
     $limitStart    = ($nowPage - 1) * $per_page;
     
     return Array(
                  'start'     => $limitStart,
                  'page' => Array(
                                  'totalnum'  => $totalNum,
                                  'totalpage' => $PageNum,
                                  'perpage'   => $per_page,
                                  'first'     => $FirstNum,
                                  'end'       => $EndNum,
                                  'previous'  => $previousNum,
                                  'nowp'      => $nowPage,
                                  'next'      => $nextNum
                                  )
            );
 }
 
 
/**
 * 分页辅助函数，风格类似baidu,google那种 以数字显示
 * 
 * @param Array page page 函数返回的结果
 * @param Int PageNum     显示的页数数量
 * @return Array 页数列表
 */
public static function pageNumStyle (Array $page, $PageNum = 15) {
    //存放结果
    $result = Array();
    $HalfPageNum = ceil ($PageNum / 2);
    //若总的页数小于 firstPageNum 则全部显示
    if ($page['totalpage'] <= $PageNum ) {
        for ($i = $page['first']; $i <= $page['end']; $i++)
            $result[] = $i;
    } else if ($page['end'] - $page['nowp'] < $HalfPageNum) {//最后的PageNum页 
            
            for ($i = $page['end'], $j = 0; $j < $PageNum; $j++, $i--)
                $result[] = $i;
            sort ($result);
    } else {

        for ($i = $page['nowp'] - 1, $j=1; $i > 0 && $j < $HalfPageNum; $i--) {
            $result[] = $i;
            $j++;
        }
        
        $HalfPageNum = $PageNum - $j;
        for ($i = $page['nowp'] + 1, $j=0; $i<= $page['end'] && $j < $HalfPageNum; $i++) {
            $result[] = $i;
            $j++;
        }
        
        $result[] = $page['nowp'];
        
        sort ($result);
    }
    
    return $result;
}
/**
 * createJpeg 根据提供的文本（四位），创建一个jpeg 图片
 * 示例：
 *  <?php
 *  @header("Expires: -1");
 *  @header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0");
 *  @header("Pragma: no-cache");
 *  header('Content-type: image/jpeg');
 *  $str = mt_rand (0,9) . mt_rand (0,9) . mt_rand (0,9) . mt_rand (0,9);
 *  $im  = createJpeg ($str);
 *  imageJpeg ($im);
 *  imagedestroy ($im);

 * @param String text 文本
 * @param String font 字体文件路径
 * @access public
 * @return imageresource
 * @author RD
 */
static function createJpeg ($text, $font) {
    //定义的背景图片，使用base64_decode 解码
    $BACKGROUND[] = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAsICAoIBwsKCQoNDAsNERwSEQ8PESIZGhQcKSQrKigkJyctMkA3LTA9MCcnOEw5PUNFSElIKzZPVU5GVEBHSEX/2wBDAQwNDREPESESEiFFLicuRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUX/wAARCAAeAFADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2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NkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD0Hf6HjuaN/c9Owqvv4yenYUu85/2v5VB4XtCfec/7X8qN/oeO5qvv7A8dzRv4yenYUB7Qsb+Mnp2FG85/2v5VBvOf9r+VJv7A8dzQHtCxv9Dx3NG/jJ6dhVffxk9Owpd5z/tfyoD2hPvOf9r+VG/0PHc1X39geO5o38ZPTsPWgPaEO8g/7f8AKk3DBAPHc1DnDFBxjO4+uKN2QTj5V4ApHFzk28YBPTsPWl3nP+3/ACqAuQAx+8entRnDFBxjO4+uKA5ybdwQDx3NG8YBI47D1qHdkE4+VeAKC5ADH7x6e1Aucn3nP+3/ACpN3BAPHc+tQ5wxQcYzuPrijdkE4+VeAKB85NvGAT07D1pd5z/t/wAqgLkAMfvHp7UZwxQcYzuPrigOc//Z';

    //背景图片
    $BACKGROUND = $BACKGROUND[array_rand ($BACKGROUND, 1)];
    //创建图片资源
    $im = imagecreatefromstring ( base64_decode ($BACKGROUND));
    //图片宽带和长度
    $tx = imagesx ($im);
    $ty = imagesy ($im);
    $ss = $tx / 4;
    // 颜色
    $black = imagecolorallocate($im, 0, 0, 0);
    $red   = imagecolorallocate($im, 255, 0, 0);
    $blue  = imagecolorallocate($im, 0, 0, 255);
    $yellow= imagecolorallocate($im, 153, 0, 255);
    $green = imagecolorallocate($im, 0, 255, 0);

    //显示字符
    //array imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )
    $color = array_rand (array ('black'=>$black, 'red'=>$red, 'blue'=>$blue, 'yellow'=>$yellow));
    imagettftext ( $im , mt_rand (12, 18) , mt_rand (-15, 30) , 5       , mt_rand (19, $ty - 3) , $$color , $font , $text{0});

    $color = array_rand (array ('black'=>$black, 'red'=>$red, 'blue'=>$blue, 'yellow'=>$yellow));
    imagettftext ( $im , mt_rand (12, 18) , mt_rand (-15, 30) , 5+$ss   , mt_rand (19, $ty - 3) , $$color , $font , $text{1});

    $color = array_rand (array ('black'=>$black, 'red'=>$red, 'blue'=>$blue, 'yellow'=>$yellow));
    imagettftext ( $im , mt_rand (12, 18) , mt_rand (-15, 30) , 5+2*$ss , mt_rand (19, $ty - 3) , $$color , $font , $text{2});

    $color = array_rand (array ('black'=>$black, 'red'=>$red, 'blue'=>$blue, 'yellow'=>$yellow));
    imagettftext ( $im , mt_rand (12, 18) , mt_rand (-15, 30) , 5+3*$ss , mt_rand (19, $ty - 3) , $$color , $font , $text{3});
    
    //画线干扰
    $color = array_rand (array ('black'=>$black, 'red'=>$red, 'blue'=>$blue, 'yellow'=>$yellow));
    imageline ( $im , mt_rand (0, $tx) , $ty/8 , $tx , $ty , $$color );
    
    $color = array_rand (array ('black'=>$black, 'red'=>$red, 'blue'=>$blue, 'yellow'=>$yellow));
    imageline ( $im , 0 , $ty , mt_rand(0,$tx) , $ty / 8 , $$color );

    //画点
    for ($x = 0; $x < $tx; ) {
    for ($y = 0; $y < $ty; ) {
         $color = array_rand (array ('black'=>$black, 'red'=>$red, 'blue'=>$blue, 'yellow'=>$yellow));
         imagesetpixel ( $im , $x , $y , $$color );
        $y += mt_rand (1, 10);
    }
    $x += mt_rand (5,15);
    }
    return $im;
}



    /**
     * get_ip 获得用户的IP,未知ip返回0.0.0.0
     * 
     * @param $isNum 是否返回数字格式
     *
     * @access public
     * @return string
     */
    public static function getip($isNum = false)
    {
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) 
            $onlineip = getenv('HTTP_CLIENT_IP');
        elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
            $onlineip = getenv('HTTP_X_FORWARDED_FOR');
        elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
            $onlineip = getenv('REMOTE_ADDR');
        elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
            $onlineip = $_SERVER['REMOTE_ADDR'];

        preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
        $onlineip = !empty($onlineipmatches[0]) ? $onlineipmatches[0] : 'unknown';
        if($onlineip=='unknown') $onlineip = '0.0.0.0';
        
        if ($isNum) {
            $onlineip = sprintf ('%u', ip2long ($onlineip));
        }
        
        return $onlineip;
    }
    
    /**
     * 上传文件到指定目录
     *
     * @param String $file_key
     * @param String $dstdir
     * @return String
     */
    public static function upfile($file_key, $dstdir)
    {
    	if (!empty($_FILES) && !empty($_FILES[$file_key]) && !empty($_FILES[$file_key]['name'])){
    		$file_ext = pathinfo($_FILES[$file_key]['name'], PATHINFO_EXTENSION);
    		$todir = APP . '/upload';
    		
    		if (!file_exists($todir . '/' . $dstdir))
    			mkdir($todir . '/' . $dstdir);
    			
    		if (!file_exists($todir . '/' . $dstdir . '/' . date("Ymd")))
    			mkdir($todir . '/' . $dstdir . '/' . date("Ymd"));
    		
    		$tofile = '/upload/' . $dstdir . '/' . date("Ymd") . '/' .date("YmdHis") . '_' . uniqid("h") . '.' . $file_ext;
    		move_uploaded_file($_FILES[$file_key]['tmp_name'], APP . $tofile);
    		
    		return $tofile;
    	}
    	
    	return "";
    }
}


/**
 * 字符串截断
 *
 * @param unknown_type $str
 * @param unknown_type $macchar
 * @param unknown_type $dot
 * @return unknown
 */
function mb_cut($str, $macchar, $dot="...")
{
	$str = strip_tags($str);
	$str = str_replace(array("&nbsp;", "\n", "\r", "\t"), " ", $str);
	$str = str_replace("  ", " ", $str);
	
	if (mb_strlen($str, "utf-8") > $macchar){
		return mb_substr($str, 0, $macchar, "utf-8") . $dot;
	}else 
		return $str;
}

function _($key)
{
	global $cfg;
	
	return $cfg['lang'][$key];
}


function getChar($arr)
{
	$max_str = "";
	$max_char = 0;
	foreach ($arr as $v)
	{
		if (mb_strlen($v['name'], "utf-8") > $max_char){
			$max_str = $v['name'];
			$max_char = mb_strlen($v['name'], "utf-8");
		}
	}
	
	$len= arial_strlen($max_str) * 6.5;
	
	if ($len < 40)
		$len = 40;
	
	return $len;
}

function arial_strlen($str)
{
	$lencounter=0;
	for($i=0;$i<strlen($str);$i++)
	{
		$ch=$str[$i];
		if(ord($ch)>128)
		{
			$i++;
			$lencounter++;
		}
		else if($ch=='f'||$ch=='i'||$ch=='j'||$ch=='l'||$ch=='r'||$ch=='I'
				||$ch=='t'||$ch=='1'
				||$ch=='.'||$ch==':'||$ch==';'||$ch=='('||$ch==')'
				||$ch=='*'||$ch=='!'||$ch=='\'')
		{
			$lencounter+=0.4;
		}
		else if($ch>='0'&&$ch<='9')
		{
			$lencounter+=0.7;
		}
		else if($ch>='a'&&$ch<='z')
		{
			$lencounter+=0.7;
		}
		else if($ch>='A'&&$ch<='Z')
		{
			$lencounter+=0.8;
		}
		else
		{
			$lencounter++;
		}
	}
	return ceil($lencounter*2);
}